package com.zw.mes.module.technology.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.zw.mes.common.JsonResult;
import com.zw.mes.entity.sys.User;
import com.zw.mes.entity.technology.ReceiveSum;
import com.zw.mes.entity.technology.Result;
import com.zw.mes.module.prodtaskmanager.model.ProdOrderQueryModel;
import com.zw.mes.module.system.service.LogService;
import com.zw.mes.module.technology.mapper.PurchasedMapper;
import com.zw.mes.module.technology.repository.ReceiveSumRepository;
import com.zw.mes.util.FileUtils;
import com.zw.mes.util.ShiroUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

import static com.zw.mes.util.BeanUtil.getNullPropertyNames;
import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;


/**
 * @author mayongfeng
 * @version 1.0.0
 * @ClassName PurchasedService.java
 * @Description TODO
 * @createTime 2021年01月29日 09:13:00
 */
@Service
@SuppressWarnings("all")
public class PurchasedService {
    @Value("${user.upload.path}")
    private String uploadPath;

    @Autowired
    private PurchasedMapper purchasedMapper;
    @Autowired
    private LogService logService;
    @Autowired
    private ReceiveSumRepository receiveSumRepository;


    public Result getSumNum(Result result) {
        int sumNum = 0;
        /** 查询提报计划为：部长审核过，外购件，非成本中心 主表加个拆分状态*/
        List<Result> withMakeReportQuery = purchasedMapper.findWithMakeReportQuery(result);
        Set<String> proList = new HashSet<>();

        /** 循环查询出原始单和变更单的计划条数*/
        for (Result result1 : withMakeReportQuery) {
            if (result1.getLssueStatus() == 1) {
                proList.add(result1.getProCode());
            }
            //原始单
            if (result1.getSheetType() == 1 && result1.getLssueStatus() == 1) {
                int countNum = purchasedMapper.findSelectPlanNum(result1.getId());
                result1.setUnplanNum(countNum);
                sumNum += countNum;
                //变更单
            } else if (result1.getSheetType() == 2 && result1.getLssueStatus() == 1) {
                int countChangeNum = purchasedMapper.findSelectChangePlanNum(result1.getId());
                result1.setUnplanNum(countChangeNum);
                sumNum += countChangeNum;
            }

        }
        result.setUnplanNum(sumNum);
        result.setUnproNum(proList.size());
        return result;


    }


    public List<Result> findWithReportQuery(Result result) {
        int sumNum = 0;
        /** 查询提报计划为：部长审核过，外购件，非成本中心 主表加个拆分状态*/
        List<Result> withMakeReportQuery = purchasedMapper.findWithMakeReportQuery(result);

//        /** 循环查询出原始单和变更单的计划条数*/
//        for (Result result1 : withMakeReportQuery) {
//            //原始单
//            if(result1.getSheetType()==1){
//                int countNum = purchasedMapper.findSelectPlanNum(result1.getId());
//                result1.setUnplanNum(countNum);
//                sumNum += countNum;
//                //变更单
//            }else if(result1.getSheetType()==2) {
//                int countChangeNum = purchasedMapper.findSelectChangePlanNum(result1.getId());
//                result1.setUnplanNum(countChangeNum);
//                sumNum += countChangeNum;
//            }
//
//        }

        return withMakeReportQuery;
    }

    /**
     * @Author mayongfeng
     * @Date 10:17 2021/2/20
     * @Description 通过Id查询该项目下的表头
     **/
    public List<Result> getSelectById(Integer id) {
        List<Result> result1 = purchasedMapper.getOne(id);
        return result1;
    }

    /**
     * @Author mayongfeng
     * @Date 10:17 2021/2/20
     * @Description 通过变更状态查询明细
     **/
    public List getSelectDetail(Integer id, Integer sheetType) {
        List<Result> results = new ArrayList<>();
        /*判断是否是变更的提报计划*/
        if (sheetType == 1) {
            results = purchasedMapper.getResultPlanList(id);
        } else if (sheetType == 2) {
            results = purchasedMapper.getResultChangeList(id);
        }
        return results;
    }

    /**
     * @Author mayongfeng
     * @Date 10:17 2021/2/20
     * @Description 通过生产令查询输出表的明细
     **/
    public List<Result> getResultDetail(String prodNo, Integer id) {
        List<Result> results = purchasedMapper.getResultDetail(prodNo, id);
        return results;
    }

    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 查询拆分页面的明细详情
     **/
    public List<Result> findPlanListQuery(Result result) {
        List<Result> resultPlanList = purchasedMapper.getResultPlanList(result.getId());
        return resultPlanList;
    }

    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 原始单自动拆分功能
     **/
    public List<Result> findautoSplit(Result result) {
        logService.saveLog("外购件拆分功能", "拆分的主键：" + result.getId());
        /*存放拆分后的list给前端*/
        List<Result> newList = new ArrayList<>();
        Result result3 = null;
        int countMark = 0;//分配标记
        int modifyTag = 0;
        /*通过Id查询计划明细条数*/
        List<Result> resultPlanList = purchasedMapper.getResultPlanListSearch(result);
        /*通过Id查询生产令数量*/
        List<Result> resultProdNum = purchasedMapper.getOneSearch(result);
        /*主表和生产令表的数据*/
        for (Result result1 : resultProdNum) {
            countMark++;
            /*明细表的数据*/
            for (Result result2 : resultPlanList) {
                modifyTag++;
                if (isInteger(result2.getNum() / result1.getProNum())) {
                    Double aivNum = ((result2.getNum() / result1.getProNum()) * result1.getProdNum());
                    result3 = new Result();
                    result3.setSplitNum(aivNum);
                    copyModel(result3, result1, result2, modifyTag);
                    newList.add(result3);
                } else {
                    result3 = new Result();
                    result3.setSplitNum(0.0);
                    if (countMark == 1) {
                        result3.setSplitNum(result2.getNum());
                    }
                    copyModel(result3, result1, result2, modifyTag);
                    newList.add(result3);
                }
            }
        }

        return newList;
    }

    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 变更单自动拆分功能
     **/
    public List<Result> autoChaSplit(Result result) {
        logService.saveLog("外购件变更单拆分功能", "拆分的主键：" + result.getId());
        /*存放拆分后的list给前端*/
        List<Result> newList = new ArrayList<>();
        Result result3 = null;
        int countMark = 0;//分配标记
        int modifyTag = 0;
        /*通过Id查询变更表的计划明细条数*/
        List<Result> resultPlanList = purchasedMapper.getResultChangeistSearch(result);
        /*通过Id查询生产令数量*/
        List<Result> resultProdNum = purchasedMapper.getOneSearch(result);
        /*主表和生产令表的数据*/
        for (Result result1 : resultProdNum) {
            countMark++;
            /*明细表的数据*/
            for (Result result2 : resultPlanList) {
                modifyTag++;
                if (isInteger(result2.getAfterNum() / result1.getProNum())) {
                    Double aivNum = ((result2.getAfterNum() / result1.getProNum()) * result1.getProdNum());
                    result3 = new Result();
                    result3.setSplitNum(aivNum);
                    copychangeModel(result3, result1, result2, modifyTag);
                    newList.add(result3);
                } else {
                    result3 = new Result();
                    result3.setSplitNum(0.0);
                    if (countMark == 1) {
                        result3.setSplitNum(result2.getAfterNum());
                    }
                    copyModel(result3, result1, result2, modifyTag);
                    newList.add(result3);
                }
            }
        }

        return newList;
    }

    /**
     * @Author mayongfeng
     * @Date 9:33 2021/2/23
     * @Description model的复制转移
     **/
    private void copyModel(Result result3, Result result1, Result result2, Integer modifyTag) {
        /*物理描述*/
        result3.setMalDesc(result2.getMalDesc());
        /*单位*/
        result3.setUnit(result2.getUnit());
        /*型号/标准号*/
        result3.setStandard(result2.getStandard());
        /*品牌*/
        result3.setBrand(result2.getBrand());
        /*备注*/
        result3.setRemark(result2.getRemark());
        /*附件*/
        result3.setUrl(result2.getUrl());
        /*项目名称*/
        result3.setProName(result1.getProName());
        /*生产令*/
        result3.setProdNo(result1.getProdNo());
        /*Id*/
        result3.setSheetId(result1.getId());
        /*planid*/
        result3.setPlanId(result2.getId());
        /*生产令里面的项目数量*/
        result3.setProdNum(result1.getProdNum());

        result3.setModifyTag(modifyTag);
    }

    /**
     * @Author mayongfeng
     * @Date 9:33 2021/2/23
     * @Description model的复制转移
     **/
    private void copychangeModel(Result result3, Result result1, Result result2, Integer modifyTag) {
        /*物理描述*/
        result3.setMalDesc(result2.getAfterMalDesc());
        /*变更原因*/
        result3.setChangeReason(result2.getChangeReason());
        /*单位*/
        result3.setUnit(result2.getAfterUnit());
        /*型号/标准号*/
        result3.setStandard(result2.getAfterStandard());
        /*品牌*/
        result3.setBrand(result2.getAfterBrand());
        /*备注*/
        result3.setRemark(result2.getAfterRemark());
        /*附件*/
        result3.setUrl(result2.getAfterUrl());
        /*项目名称*/
        result3.setProName(result1.getProName());
        /*生产令*/
        result3.setProdNo(result1.getProdNo());
        /*Id*/
        result3.setSheetId(result1.getId());
        /*planid*/
        result3.setPlanId(result2.getId());
        /*生产令里面的项目数量*/
        result3.setProdNum(result1.getProdNum());
        result3.setChangePlanId(result2.getPlanId());
        result3.setModifyTag(modifyTag);
    }

    /**
     * @Author mayongfeng
     * @Date 16:41 2021/2/22
     * @Description 判断double类型是否为整数
     **/
    public static boolean isInteger(double d) {
        if ((int) d == d) { //强制转换du后会丢失精度zhi,如果丢dao失精度的数和原数zhuan相等，说明就是shu整数
            return true;
        } else {
            return false;
        }
    }

    /**
     * @Author mayongfeng
     * @Date 16:31 2021/2/23
     * @Description 验证拆分后的数量和提报的数量是否相同
     **/
    public int isSumNum(List<Result> prodPlaDetList) {
        logService.saveLog("外购件原始单拆分提交", "生产令");
        Map<Integer, Double> map = new HashMap<Integer, Double>();
        for (Result result : prodPlaDetList) {
            Integer planId = result.getPlanId();
            if (map.containsKey(planId)) {
                map.put(planId, numberDouble(map.get(planId), result.getSplitNum()));
            } else {
                map.put(planId, result.getSplitNum());
            }
        }

        /** 循环取map的值*/
        for (Map.Entry<Integer, Double> mapz : map.entrySet()) {
            /** 查询原计划单的明细*/
            Result planDatil = purchasedMapper.getPlanid(mapz.getKey());
            if (!planDatil.getNum().toString().equals(mapz.getValue().toString())) {
                return -2;
            }
        }
        /** 添加用的实体类*/
        Result addResult = null;
        Result sheetResult = null;
        Result planResult = null;
        int i = 0;
        int sheetId = 0;
        /** 拆分成功以后存放到提报计划输出表*/
        for (Result result : prodPlaDetList) {
            sheetId = result.getSheetId();
            addResult = new Result();
            sheetResult = new Result();
            planResult = new Result();
            sheetResult = purchasedMapper.getSheetResult(result.getSheetId());
            planResult = purchasedMapper.getplanResult(result.getPlanId());
            copy(sheetResult, addResult);
            copy(planResult, addResult);
            addResult.setProdNo(result.getProdNo());
            addResult.setSplitNum(result.getSplitNum());
            addResult.setLssueStatus(1);
            addResult.setProNum(result.getProdNum());
            addResult.setExtendUrl(planResult.getUrl());
            addResult.setSpecial(sheetResult.getMalType());
            addResult.setRecMark(0);
            addResult.setRawSplit(1);
            if (addResult.getSheetType() == 1) {
                addResult.setChangeMark(0);
            } else if (addResult.getSheetType() == 2) {
                addResult.setChangeMark(1);
            }
            i = purchasedMapper.addResult(addResult);

        }
        purchasedMapper.updateSheetId(sheetId);
        /** 通过Id获得主单信息*/
        Result sheetResult1 = purchasedMapper.getSheetResult(sheetId);
        /** 首次接收时在接收记录表里面添加记录信息*/
        ReceiveSum str = receiveSumRepository.findByProCodeAndPartAndSpecial(sheetResult1.getProCode(), sheetResult1.getPart(), sheetResult1.getMalType());
        /** 判断集合为不为null*/
        if (null == str || "".equals(str)) {
            /** 如果记录表里面为空就向记录表里面添加接收记录*/
            ReceiveSum receiveSum = new ReceiveSum();
            receiveSum.setProCode(sheetResult1.getProCode());
            receiveSum.setProName(sheetResult1.getProName());
            receiveSum.setProNum(sheetResult1.getProNum());
            receiveSum.setPart(sheetResult1.getPart());
            receiveSum.setSpecial(sheetResult1.getMalType());
            receiveSum.setOutStatus(1);
            receiveSum.setCardStatus(0);
            receiveSum.setMakeStatus(0);
            receiveSum.setPaintStatus(0);
            receiveSumRepository.save(receiveSum);
        } else if (str.getOutStatus() == 0) {
            str.setOutStatus(1);
            receiveSumRepository.save(str);
        }


        return i;
    }

    /**
     * @Author mayongfeng
     * @Date 16:31 2021/2/23
     * @Description 验证变更拆分后的数量和提报的数量是否相同
     **/
    @Transactional(rollbackFor = Exception.class)
    public int isSumChaNum(List<Result> prodChaDetList) {
        logService.saveLog("外购件变更单拆分提交", "生产令");
        Map<Integer, Double> map = new HashMap<Integer, Double>();
        for (Result result : prodChaDetList) {
            /** 变更的时候planId是chang表里面的Id*/
            Integer planId = result.getPlanId();
            if (map.containsKey(planId)) {
                map.put(planId, numberDouble(map.get(planId), result.getSplitNum()));
            } else {
                map.put(planId, result.getSplitNum());
            }
        }

        /** 循环取map的值*/
        for (Map.Entry<Integer, Double> mapz : map.entrySet()) {
            /** 查询变更单计划单的明细*/
            Result changeDatil = purchasedMapper.getChangeid(mapz.getKey());
            if (!changeDatil.getAfterNum().toString().equals(mapz.getValue().toString())) {
                return -2;
            }
        }
        /** 添加用的实体类*/
        Result addResult = null;
        Result sheetResult = null;
        Result changeResult = null;
        int i = 0;
        int sheetId = 0;
        /** 拆分成功以后存放到提报计划输出表*/
        for (Result result : prodChaDetList) {
            sheetId = result.getSheetId();
            addResult = new Result();
            sheetResult = new Result();
            changeResult = new Result();
            sheetResult = purchasedMapper.getSheetResult(result.getSheetId());
            changeResult = purchasedMapper.getChangeid(result.getPlanId());
            copy(sheetResult, addResult);
            copy(changeResult, addResult);
            addResult.setProdNo(result.getProdNo());
            addResult.setSplitNum(result.getSplitNum());
            addResult.setProNum(result.getProdNum());
            addResult.setExtendUrl(changeResult.getAfterUrl());
            addResult.setSpecial(sheetResult.getMalType());
            addResult.setRecMark(0);
            if (addResult.getSheetType() == 1) {
                addResult.setChangeMark(0);
                i = purchasedMapper.updateResult(addResult);
            } else if (addResult.getSheetType() == 2) {
                addResult.setChangeMark(1);
                addResult.setLssueStatus(1);
                i = purchasedMapper.updateResult2(addResult);
            }
            i = purchasedMapper.updateSheetId(sheetId);
        }
        return i;
    }

    /**
     * @Author mayongfeng
     * @Date 10:09 2021/2/20
     * @Description 在输出表更改拆分后的数据的状态
     **/
    @Transactional(rollbackFor = Exception.class)
    public int modifyLssue(Integer resultAndSheetId, String prodNo) {
        int i = 0;
        /**判断外购件计划在拆分后下达时，生产令是否删除，如果删除生产令不允许下达拆分计划*/
        int repProdNo = purchasedMapper.findSelectProdNoDel(prodNo);
        List<Result> selResuleSheetId = purchasedMapper.selResuleSheetId(resultAndSheetId);
        if (repProdNo != 0) {
            /**查询判断当前下达的生产令是否为主单的最后一个计划，如果是者更新主单下达状态否则变更单不能下达*/
            int lssSta = purchasedMapper.findSelectCountResult(prodNo, selResuleSheetId.get(0).getSheetId());
            if (lssSta == 0) {
                i = purchasedMapper.updateChaSheetId(selResuleSheetId.get(0).getSheetId());
            }
            i = purchasedMapper.modifyLssue(prodNo, selResuleSheetId.get(0).getSheetId());
            logService.saveLog("外购件拆分多个生产令拆分后的下达", "生产令" + prodNo);
        } else {
            i = -1;
        }
        return i;
    }

    /**
     * @Author mayongfeng
     * @Date 13:41 2021/3/3
     * @Description 将主表的数据添加到输出表并且修改下达状态
     **/
    public JsonResult addResultAndModifyLssue(Integer resultAndSheetId) {
        JsonResult jsonResult = new JsonResult();
        try {
            /*通过主表Id查询原始单明细表的集合*/
            List<Result> planList = purchasedMapper.getResultPlanList(resultAndSheetId);
            /*通过主表Id查询主表信息关联生产令表*/
            List<Result> result = purchasedMapper.getOne(resultAndSheetId);
            //是否包含重复数据
            boolean isHaveRepeatResult = false;
            for (Result result1 : planList) {
                result1.setSheetId(result.get(0).getId());
                result1.setProCode(result.get(0).getProCode());
                result1.setProName(result.get(0).getProName());
                result1.setProNum(result.get(0).getProdNum());
                result1.setProUnit(result.get(0).getProUnit());
                result1.setMalType(result.get(0).getMalType());
                result1.setPart(result.get(0).getPart());
                /** 外购件状态*/
                result1.setReportType(result.get(0).getReportType());
                //根据主单ID，计划ID，项目号，项目名称，项目数量，项目单位，物料类型，部分，提报类型验证是否有重复数据
                //避免单用户重复点击下达和多用户点击相同计划下达，所以不验证下达人信息只验证计划信息
                if (purchasedMapper.queryResultCount(result1) > 0) {
                    isHaveRepeatResult = true;
                    break;
                }
            }
            //如果有重复数据执行下面代码
            if (isHaveRepeatResult) {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("尊敬的用户，您不可重复下达！");
            }
            //如果无重复数据执行插入数据操作
            else {
                logService.saveLog("外购件一个生产令的下达", "主键" + resultAndSheetId);
                /** 首次接收时在接收记录表里面添加记录信息*/
                ReceiveSum str = receiveSumRepository.findByProCodeAndPartAndSpecial(result.get(0).getProCode(), result.get(0).getPart(), result.get(0).getMalType());
                /** 判断集合为不为null*/
                if (null == str || "".equals(str)) {
                    /** 如果记录表里面为空就向记录表里面添加接收记录*/
                    ReceiveSum receiveSum = new ReceiveSum();
                    receiveSum.setProCode(result.get(0).getProCode());
                    receiveSum.setProName(result.get(0).getProName());
                    receiveSum.setProNum(result.get(0).getProNum());
                    receiveSum.setPart(result.get(0).getPart());
                    receiveSum.setSpecial(result.get(0).getMalType());
                    receiveSum.setOutStatus(1);
                    receiveSum.setCardStatus(0);
                    receiveSum.setMakeStatus(0);
                    receiveSum.setPaintStatus(0);
                    receiveSumRepository.save(receiveSum);
                } else if (str.getOutStatus() == 0) {
                    str.setOutStatus(1);
                    receiveSumRepository.save(str);
                }
                int i = 0;
                /*循环添加到输出表里面的数据*/
                for (Result result1 : planList) {
                    result1.setPlanId(result1.getId());
                    result1.setSheetId(result.get(0).getId());
                    result1.setProCode(result.get(0).getProCode());
                    result1.setProName(result.get(0).getProName());
                    result1.setProNum(result.get(0).getProdNum());
                    result1.setProUnit(result.get(0).getProUnit());
                    result1.setMalType(result.get(0).getMalType());
                    result1.setPart(result.get(0).getPart());
                    /** 外购件状态*/
                    result1.setReportType(result.get(0).getReportType());
                    result1.setPostName(result.get(0).getPostName());
                    result1.setPostTel(result.get(0).getPostTel());
                    result1.setPostDept(result.get(0).getPostDept());
                    /** 变更标识 0=未变更，1=已变更*/
                    result1.setChangeMark(0);
                    result1.setRecMark(0);
                    /** 状态 0=删除，1=正常 */
                    result1.setStatus(1);
                    result1.setSpecial(result.get(0).getSpecial());
                    result1.setReviewer(result.get(0).getReviewer());
                    result1.setVerifier(result.get(0).getVerifier());
                    result1.setBranchName(result.get(0).getBranchName());
                    result1.setExtendUrl(result1.getUrl());
                    /** 下发状态：1=未下发，2=已下发*/
                    result1.setLssueStatus(2);
                    result1.setSplitNum(result1.getNum());
                    result1.setLssueTime(new Date());
                    result1.setProdNo(result.get(0).getProdNo());
                    i = purchasedMapper.addResult(result1);
                }
                i = purchasedMapper.updateChaSheetId(resultAndSheetId);
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setMsg("尊敬的用户，下达成功！");
            }
        } catch (Exception e) {
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("尊敬的用户，下达计划异常强联系管理员！");
        }
        return jsonResult;
    }


/********************************************工具方法*******************************************************************/
    /**
     * 复制对象，并排除空值属性
     *
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copy(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }

    /**
     * @Author mayongfeng
     * @Date 11:04 2021/3/5
     * @Description double类型的数据进行转换在做运算
     **/
    public static Double numberDouble(Double a, Double b) {
        DecimalFormat df = new DecimalFormat("0.0");
        BigDecimal b1 = new BigDecimal(df.format(a));
        BigDecimal b2 = new BigDecimal(df.format(b));
        return b1.add(b2).doubleValue();
    }


    public List<Result> getChangeById(Integer id) {
        List<Result> results = purchasedMapper.getResultChangeList(id);
        return results;
    }

    /**
     * 主表变更数据下达并且修改到输出表
     */
    public int chaSheetRelease(Result result) {
        int i = 0;
        /** 判断被变更的主单数据是否是下达*/
        if (result.getSheetId() != null || "".equals(result.getSheetId())) {
            /** 通过变更主单的sheetId查询被变更的主单下达状态*/
            Result sheetResult = purchasedMapper.getSheetResult(result.getSheetId());
            /** 判断被变更的数据是否下达1=未下达,2=已下达*/
            if (sheetResult.getLssueStatus() == 1) {
                return -2;
            } else if (sheetResult.getLssueStatus() == 2) {
                List<Result> resultList = purchasedMapper.getResultChangeList(result.getId());
                for (Result result1 : resultList) {
                    i = purchasedMapper.updatePlandId(result1);

                }
                i = purchasedMapper.updateChaSheetId(result.getId());
            }
        }
        return i;
    }

    public int getSheetResult(Integer sheetId) {
        int i = 0;
        Result result = purchasedMapper.getSheetResult(sheetId);
        if (result.getRawSplit() == 0) {
            i = -1;
        } else if (result.getRawSplit() == 1) {
            i = 1;
        }
        return i;
    }

    public Result getResultByid(Integer id) {
        return purchasedMapper.getChangeid(id);
    }

    public Result getPlanByid(Integer id) {
        return purchasedMapper.getPlanid(id);
    }

    /**
     * 删除已拆分的未下达提报计划
     * 科长让做的提报计划删除功能，按照生产令判断，生产令删除才可以删除提报计划
     *
     * @param result
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int resDelPlanSplit(Result result) {
        int i = 0;
        int prod = purchasedMapper.selectProdOrd(result);
        /**删除拆分计划时，验证生产令是否存在*/
        if (prod == 0) {
            i = purchasedMapper.updateResPlanSplit(result);
        } else if (prod != 0) {
            i = -1;
        }
        /**当所有拆分的外购件计划全部删除完成后，还原外购件计划主表拆分状态*/
        int repStatus = purchasedMapper.selRepResuleStatus(result);
        if (repStatus == 0) {
            List<Result> selSheetId = purchasedMapper.selectRepSheetId(result.getProdNo());
            i = purchasedMapper.updateRepSheetSpl(selSheetId.get(0).getSheetId());
        }
        /**当生产令拆分后，外购件计划也拆分的情况下，删除一个拆分后的外购计划时判断当前拆分计划是否全部下达，
         如果全部下达修改主单已下达状态*/
        int selDelRepStatus = purchasedMapper.selRepResuleDel(result);
        if (selDelRepStatus == 0) {
            List<Result> flanSheetId = purchasedMapper.selectRepSheetId(result.getProdNo());
            i = purchasedMapper.updateChaSheetId(flanSheetId.get(0).getSheetId());
        }
        logService.saveLog("删除拆分的生产令", "生产令" + result.getProdNo());
        return i;
    }

    /**
     * 查询未分配外购件数量
     *
     * @return
     */
    public int selectReportCount() {
        return purchasedMapper.selectReportCount();
    }

    /***
     * 驳回设计院提报外购件计划
     * @param result
     * @return
     */
    public int chaSheetReturn(Result result) {
        //修改vw_sys_verify_process表状态
        int i = purchasedMapper.chaSheetReturn(result);
        //修改vw_rep_sheet表状态
        int k = purchasedMapper.chaSheetReturn1(result);
        logService.saveLog("退回外购件计划", "id" + result.getId());
        return purchasedMapper.chaSheetReturn(result);
    }

    /**
     *导出原始单导出方法
     * @param response
     * @param param
     */
    @Transactional
    public void exportExcel(Integer sheetId,HttpServletResponse response)
    {
//        List<Result> results = purchasedMapper.exporResultPallList(sheetId);
//
//        // 创建HSSFWorkbook对象(excel的文档对象)
//        HSSFWorkbook wb = new HSSFWorkbook();
//        // 建立新的sheet对象（excel的表单）
//        HSSFSheet hssfSheet = wb.createSheet("sheet1");
//        // 在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
//        HSSFRow hssfRow = hssfSheet.createRow(0);
//        // 创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
//        HSSFCell hssfCell = hssfRow.createCell(0);
//
//        hssfRow.createCell(0).setCellValue("物料名称");
//        hssfRow.createCell(1).setCellValue("数量");
//        hssfRow.createCell(2).setCellValue("单位");
//        hssfRow.createCell(3).setCellValue("型号");
//        hssfRow.createCell(4).setCellValue("品牌");
//        hssfRow.createCell(5).setCellValue("备注");
//
//        for(int i = 0; i < results.size(); i++)
//        {
//            HSSFRow row = hssfSheet.createRow(i + 1);
//            row.createCell(0).setCellValue(results.get(i).getMalDesc());
//            row.createCell(1).setCellValue(results.get(i).getNum());
//            row.createCell(2).setCellValue(results.get(i).getUnit());
//            row.createCell(3).setCellValue(results.get(i).getStandard());
//            row.createCell(4).setCellValue(results.get(i).getBrand());
//            row.createCell(5).setCellValue(results.get(i).getRemark());
//        }
//        try {
//            OutputStream output = response.getOutputStream();
//            response.reset();
//            response.setHeader("Content-disposition", "attachment; filename=" + new String( "外购件计划明细.xls".getBytes("gb2312"), "ISO8859-1" ));
//            response.setContentType("application/msexcel");
//            wb.write(output);
//            output.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        //控制样式，支持.xlsx格式，这两部分代码到好使，下面这段代码有AI优化部分
        XSSFWorkbook wb = null; // 1. 替换为XSSFWorkbook
        try {
            List<Result> results = purchasedMapper.exporResultPallList(sheetId);

            // 2. 所有POI相关对象都替换为XSSF前缀
            wb = new XSSFWorkbook();
            XSSFSheet xssfSheet = wb.createSheet("sheet1");
            XSSFCellStyle cellStyle = createCellStyle(wb); // 辅助方法也需同步修改

            // 3. 表头行：替换为XSSFRow、XSSFCell
            XSSFRow xssfRow = xssfSheet.createRow(0);
            String[] headers = {"序号", "物料名称", "数量", "单位", "型号", "品牌", "备注"};
            for (int i = 0; i < headers.length; i++) {
                XSSFCell cell = xssfRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(cellStyle);
            }

            // 4. 数据行：同样替换为XSSF前缀
            for (int i = 0; i < results.size(); i++) {
                XSSFRow row = xssfSheet.createRow(i + 1);
                Result result = results.get(i);

                XSSFCell seqCell = row.createCell(0);
                seqCell.setCellValue(i + 1);
                seqCell.setCellStyle(cellStyle);

                // 物料名称（索引1）：避免null，空值显示空字符串
                XSSFCell malDescCell = row.createCell(1);
                malDescCell.setCellValue(result.getMalDesc() != null ? result.getMalDesc() : "");
                malDescCell.setCellStyle(cellStyle);

                // 数量（索引2）：根据Result中num的类型适配（若为BigDecimal/Integer直接赋值，字符串需转换）
                XSSFCell numCell = row.createCell(2);
                if (result.getNum() != null) {
                    // 若num是数字类型（Integer/BigDecimal/Double），直接设置数值类型
                    numCell.setCellValue(result.getNum().toString()); // 转为字符串避免科学计数法（或直接setCellValue(数字)）
                } else {
                    numCell.setCellValue("");
                }
                numCell.setCellStyle(cellStyle);

                // 单位（索引3）：避免null
                XSSFCell unitCell = row.createCell(3);
                unitCell.setCellValue(result.getUnit() != null ? result.getUnit() : "");
                unitCell.setCellStyle(cellStyle);

                // 型号（索引4）：避免null
                XSSFCell standardCell = row.createCell(4);
                standardCell.setCellValue(result.getStandard() != null ? result.getStandard() : "");
                standardCell.setCellStyle(cellStyle);

                // 品牌（索引5）：避免null
                XSSFCell brandCell = row.createCell(5);
                brandCell.setCellValue(result.getBrand() != null ? result.getBrand() : "");
                brandCell.setCellStyle(cellStyle);

                // 备注（索引6）：避免null
                XSSFCell remarkCell = row.createCell(6);
                remarkCell.setCellValue(result.getRemark() != null ? result.getRemark() : "");
                remarkCell.setCellStyle(cellStyle);
            }

            // 5. 列宽调整逻辑不变
            int[] columnWidths = {8 * 256, 20 * 256, 10 * 256, 8 * 256, 15 * 256, 12 * 256, 25 * 256};
            for (int i = 0; i < columnWidths.length; i++) {
                xssfSheet.setColumnWidth(i, columnWidths[i]);
            }

            // 6. 响应配置：替换文件名和ContentType
            try (OutputStream output = response.getOutputStream()) {
                response.reset();
                // 文件名扩展名改为.xlsx（编码逻辑不变）
                response.setHeader("Content-disposition",
                        "attachment; filename=" + new String("外购件计划明细.xlsx".getBytes("gb2312"), "ISO8859-1"));
                // 替换为.xlsx对应的MIME类型
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

                wb.write(output);
                output.flush();
            }

        } catch (Exception e) {
            // 异常处理逻辑不变...
        } finally {
            // 关闭XSSFWorkbook（逻辑不变）
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 外购件分配变更单导出
     * @param sheetId
     * @param response
     */
    @Transactional
    public void exportExcelChange(Integer sheetId,HttpServletResponse response)
    {
        //控制样式，支持.xlsx格式，这两部分代码到好使，下面这段代码有AI优化部分
        XSSFWorkbook wb = null; // 1. 替换为XSSFWorkbook
        try {
            List<Result> resultChange = purchasedMapper.exporResultPallChangeList(sheetId);

            // 2. 所有POI相关对象都替换为XSSF前缀
            wb = new XSSFWorkbook();
            XSSFSheet xssfSheet = wb.createSheet("sheet1");
            XSSFCellStyle cellStyle = createCellStyle(wb); // 辅助方法也需同步修改

            // 3. 表头行：替换为XSSFRow、XSSFCell
            XSSFRow xssfRow = xssfSheet.createRow(0);
            String[] headers = {"序号", "物料名称", "数量", "单位", "型号", "品牌", "备注"};
            for (int i = 0; i < headers.length; i++) {
                XSSFCell cell = xssfRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(cellStyle);
            }

            // 4. 数据行：同样替换为XSSF前缀
            for (int i = 0; i < resultChange.size(); i++) {
                XSSFRow row = xssfSheet.createRow(i + 1);
                Result resultC = resultChange.get(i);

                XSSFCell seqCell = row.createCell(0);
                seqCell.setCellValue(i + 1);
                seqCell.setCellStyle(cellStyle);

                // 物料名称（索引1）：避免null，空值显示空字符串
                XSSFCell malDescCell = row.createCell(1);
                malDescCell.setCellValue(resultC.getAfterMalDesc() != null ? resultC.getAfterMalDesc() : "");
                malDescCell.setCellStyle(cellStyle);

                // 数量（索引2）：根据Result中num的类型适配（若为BigDecimal/Integer直接赋值，字符串需转换）
                XSSFCell numCell = row.createCell(2);
                if (resultC.getAfterNum() != null) {
                    // 若num是数字类型（Integer/BigDecimal/Double），直接设置数值类型
                    numCell.setCellValue(resultC.getAfterNum().toString()); // 转为字符串避免科学计数法（或直接setCellValue(数字)）
                } else {
                    numCell.setCellValue("");
                }
                numCell.setCellStyle(cellStyle);

                // 单位（索引3）：避免null
                XSSFCell unitCell = row.createCell(3);
                unitCell.setCellValue(resultC.getAfterUnit() != null ? resultC.getAfterUnit() : "");
                unitCell.setCellStyle(cellStyle);

                // 型号（索引4）：避免null
                XSSFCell standardCell = row.createCell(4);
                standardCell.setCellValue(resultC.getAfterStandard() != null ? resultC.getAfterStandard() : "");
                standardCell.setCellStyle(cellStyle);

                // 品牌（索引5）：避免null
                XSSFCell brandCell = row.createCell(5);
                brandCell.setCellValue(resultC.getAfterBrand() != null ? resultC.getAfterBrand() : "");
                brandCell.setCellStyle(cellStyle);

                // 备注（索引6）：避免null
                XSSFCell remarkCell = row.createCell(6);
                remarkCell.setCellValue(resultC.getAfterRemark() != null ? resultC.getAfterRemark() : "");
                remarkCell.setCellStyle(cellStyle);
            }

            // 5. 列宽调整逻辑不变
            int[] columnWidths = {8 * 256, 20 * 256, 10 * 256, 8 * 256, 15 * 256, 12 * 256, 25 * 256};
            for (int i = 0; i < columnWidths.length; i++) {
                xssfSheet.setColumnWidth(i, columnWidths[i]);
            }

            // 6. 响应配置：替换文件名和ContentType
            try (OutputStream output = response.getOutputStream()) {
                response.reset();
                // 文件名扩展名改为.xlsx（编码逻辑不变）
                response.setHeader("Content-disposition",
                        "attachment; filename=" + new String("外购件计划变更单明细.xlsx".getBytes("gb2312"), "ISO8859-1"));
                // 替换为.xlsx对应的MIME类型
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

                wb.write(output);
                output.flush();
            }

        } catch (Exception e) {
            // 异常处理逻辑不变...
        } finally {
            // 关闭XSSFWorkbook（逻辑不变）
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 辅助方法：创建单元格样式
     */
    private XSSFCellStyle createCellStyle(XSSFWorkbook wb) {
        XSSFFont font = wb.createFont(); // 替换为XSSFFont
        font.setFontName("宋体");
        font.setFontHeightInPoints((short) 12);

        XSSFCellStyle cellStyle = wb.createCellStyle(); // 替换为XSSFCellStyle
        cellStyle.setFont(font);
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setWrapText(false);
        return cellStyle;
    }
}

